package al.xc.service.impl;

import al.xc.common.util.GsonUtils;
import al.xc.common.util.SingleUtils;
import al.xc.common.util.TimeUtils;
import al.xc.data.model.wechat.GlobalSessionInfo;
import al.xc.redis.RedisConnectManager;
import al.xc.service.IWechatAuthorService;
import org.springframework.stereotype.Service;

import java.util.Calendar;
import java.util.Date;

@Service
public class WechatAuthorServiceImpl implements IWechatAuthorService {

    private RedisConnectManager connect = SingleUtils.instance(RedisConnectManager.class);

    /**
     * 查找微信全局sessonkey
     *
     * @param appid
     * @return
     * @throws Exception
     */
    public GlobalSessionInfo find(String appid) throws Exception {
        String json = connect.connect().hget("WX:GLOBAL:SESSION_KEY", appid);
        if (null != json) {
            return GsonUtils.fromJson(json, GlobalSessionInfo.class);
        }
        return null;
    }

    /**
     * 设置微信全局sessionkey
     *
     * @param appid
     * @param token
     * @param expire
     * @return
     * @throws Exception
     */
    public GlobalSessionInfo insert(String appid, String token, Integer expire) throws Exception {
        GlobalSessionInfo sessionInfo = new GlobalSessionInfo();
        sessionInfo.setSessionKey(token);
        sessionInfo.setExpireTime(TimeUtils.addTime(new Date(), Calendar.SECOND, expire));
        connect.connect().hset("WX:GLOBAL:SESSION_KEY", appid, GsonUtils.toJson(sessionInfo));
        return sessionInfo;
    }
}
